/**
 * Created by lining on 18/6/24.
 */
// 0xd4abe81bebc66c0f4ea73dd27a0958360c4bb005
var Web3 = require('web3');
var fs = require('fs');
var Tx = require('ethereumjs-tx');
var ethabi = require('web3-eth-abi');
class EtherData
{
    /*
    addNote
    updateNote
    getNote
    queryTransactionStatus
     */
    constructor()
    {
        //  设置CloudNoteService合约地址
        this.contractAddress = '0x4044117811266661bc59d03a448cef5c7d159dfb';
        // 1 GWei
        this.gasPrice = '0x3B9ACA00'

        this.web3 = new Web3(new Web3.providers.HttpProvider('https://kovan.infura.io/v3/eb070771c02d4822bf7eb7b53282ab4e'));

        this.abi = JSON.parse(fs.readFileSync('./CloudNoteService_sol_CloudNoteService.abi').toString());

        this.contract = this.web3.eth.contract(this.abi).at(this.contractAddress);



    }
    getNonce()
    {
        var nonce = this.web3.eth.getTransactionCount("0x97d2ab3db82c57e85c7aaf04cafadf38cc7f238b")
        return nonce;
    }
    addUpdateNote(id,name,content,notefun)
    {
        var estimateGas = this.web3.eth.estimateGas({
            to:this.contractAddress,
            data:notefun
        })
        var nonce = global.getNextNonce();
        var rawTx = {
            nonce:nonce,   // nonce值，每笔交易加1
            gasPrice: this.gasPrice,
            gasLimit: estimateGas,   //  发布交易预估消耗的gas数
            to:this.contractAddress,
            value:'0x00',
            data:notefun
        }
        //  开始用private key
        var tx = new Tx(rawTx);
        const privateKey = new Buffer('d12a613e5efdff6770dd804028dbc7f36365910f5e8401bb270ce466b6359431','hex');

        tx.sign(privateKey);

        var serializedTx = tx.serialize();
        return this.web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'));

    }
    // 添加云笔记
    addNote(id,name,content)
    {
        var addNote = this.contract.addNote.getData(id, name, content);
        return this.addUpdateNote(id,name,content,addNote);

    }
    //  更新笔记
    updateNote(id,name,content)
    {
        var updateNote = this.contract.updateNote.getData(id, name,content);
        return this.addUpdateNote(id,name,content,updateNote);

    }
    // 根据用户ID和笔记名称获取笔记内容
    getNote(id,name)
    {
        var getNote = this.contract.getNote.getData(id,name);
        var result = this.web3.eth.call({
            to:this.contractAddress,
            data: getNote
        });
        return ethabi.decodeParameter('string',result);
    }

    //  返回交易状态，1：成功, 0：失败   null：未处理
    queryTransactionStatus(hash)
    {
        var result = this.web3.eth.getTransactionReceipt(hash);
        if(result != null)
        {
            return parseInt(result.status,16);
        }
        return null;
    }
}
module.exports = EtherData;
